<template>
  <div class="user-management-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <div class="header-icon">
          <el-icon><User /></el-icon>
        </div>
        <div class="header-content">
          <h1>用户管理</h1>
          <p>管理用户信息、余额和游玩时间，查看用户数据统计</p>
        </div>
      </div>
      <div class="header-actions">
        <el-button
          size="large"
          @click="exportUsers"
          class="action-btn secondary"
        >
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
        <el-button
          type="primary"
          size="large"
          @click="refreshData"
          class="action-btn primary"
          :loading="loading"
        >
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
      <div class="header-decoration">
        <div class="decoration-circle"></div>
        <div class="decoration-dots">
          <span v-for="i in 4" :key="i" class="dot"></span>
        </div>
      </div>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-card">
        <div class="filter-header">
          <div class="filter-title">
            <el-icon><Search /></el-icon>
            <span>筛选与搜索</span>
          </div>
          <div class="filter-actions">
            <el-button
              text
              @click="resetFilter"
              class="reset-btn"
            >
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>

        <div class="filter-content">
          <div class="filter-group">
            <label class="filter-label">用户名</label>
            <el-input
              v-model="filterForm.username"
              placeholder="请输入用户名"
              clearable
              class="filter-input"
            />
          </div>

          <div class="filter-group">
            <label class="filter-label">手机号</label>
            <el-input
              v-model="filterForm.phone"
              placeholder="请输入手机号"
              clearable
              class="filter-input"
            />
          </div>

          <div class="filter-group">
            <label class="filter-label">用户角色</label>
            <el-select
              v-model="filterForm.role"
              placeholder="选择角色"
              clearable
              class="filter-select"
            >
              <el-option label="全部角色" value="" />
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </div>

          <div class="filter-group">
            <label class="filter-label">账户状态</label>
            <el-select
              v-model="filterForm.status"
              placeholder="选择状态"
              clearable
              class="filter-select"
            >
              <el-option label="全部状态" value="" />
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </div>

          <div class="filter-group search-group">
            <label class="filter-label">快速操作</label>
            <div class="search-actions">
              <el-button
                type="primary"
                @click="searchUsers"
                class="search-btn"
              >
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据可视化切换 -->
    <div class="toggle-section">
      <div class="toggle-card">
        <div class="toggle-header">
          <div class="toggle-title">
            <el-icon><DataAnalysis /></el-icon>
            <span>数据可视化</span>
          </div>
          <div class="toggle-controls">
            <el-switch
              v-model="showCharts"
              size="large"
              active-text="显示图表"
              inactive-text="隐藏图表"
              @change="handleChartsToggle"
              class="chart-switch"
            />
            <el-button
              v-if="showCharts"
              type="primary"
              size="small"
              @click="refreshCharts"
              class="refresh-charts-btn"
            >
              <el-icon><Refresh /></el-icon>
              刷新图表
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 用户统计图表 -->
    <div v-show="showCharts" class="charts-section">
      <div class="charts-grid">
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">
              <el-icon><TrendCharts /></el-icon>
              <span>用户注册趋势</span>
            </div>
            <el-tag size="small" type="primary" class="chart-tag">基于真实注册时间</el-tag>
          </div>
          <div class="chart-container">
            <v-chart
              :option="userRegistrationChartOption"
              :style="{ height: '280px', width: '100%' }"
              autoresize
            />
          </div>
        </div>

        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">
              <el-icon><PieChart /></el-icon>
              <span>用户角色分布</span>
            </div>
            <el-tag size="small" type="success" class="chart-tag">实时数据</el-tag>
          </div>
          <div class="chart-container">
            <v-chart
              :option="userRoleChartOption"
              :style="{ height: '280px', width: '100%' }"
              autoresize
            />
          </div>
        </div>

        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">
              <el-icon><Histogram /></el-icon>
              <span>用户余额分布</span>
            </div>
            <el-tag size="small" type="warning" class="chart-tag">动态统计</el-tag>
          </div>
          <div class="chart-container">
            <v-chart
              :option="userBalanceChartOption"
              :style="{ height: '280px', width: '100%' }"
              autoresize
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="table-section">
      <div class="table-card">
        <div class="table-header">
          <div class="table-title">
            <el-icon><List /></el-icon>
            <span>用户列表</span>
            <span class="user-count">共 {{ pagination.total }} 位用户</span>
          </div>
          <div class="table-actions">
            <el-button-group>
              <el-button
                type="primary"
                @click="exportUsers"
                class="action-btn"
              >
                <el-icon><Download /></el-icon>
                导出数据
              </el-button>
              <el-button
                @click="fetchUsers"
                class="action-btn"
                :loading="loading"
              >
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </el-button-group>
          </div>
        </div>

        <div class="table-container">
          <el-table
            :data="users"
            v-loading="loading"
            stripe
            class="modern-table"
            :header-cell-style="{
              background: '#f8fafc',
              color: '#374151',
              fontWeight: '600',
              borderBottom: '2px solid #e2e8f0'
            }"
            :row-style="{ height: '60px' }"
          >
            <el-table-column prop="id" label="ID" width="80" align="center">
              <template #default="scope">
                <span class="user-id">#{{ scope.row.id }}</span>
              </template>
            </el-table-column>

            <el-table-column label="用户信息" width="200">
              <template #default="scope">
                <div class="user-info">
                  <div class="user-avatar">
                    <el-avatar :size="40" :src="scope.row.avatar">
                      {{ scope.row.username?.charAt(0)?.toUpperCase() }}
                    </el-avatar>
                  </div>
                  <div class="user-details">
                    <div class="username">{{ scope.row.username }}</div>
                    <div class="real-name">{{ scope.row.real_name || '未设置' }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="phone" label="手机号" width="130">
              <template #default="scope">
                <span class="phone-number">{{ scope.row.phone || '未绑定' }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="email" label="邮箱" width="180">
              <template #default="scope">
                <span class="email-text">{{ scope.row.email || '未设置' }}</span>
              </template>
            </el-table-column>

            <el-table-column label="余额" width="120" align="center">
              <template #default="scope">
                <div class="balance-info">
                  <span class="balance-amount">¥{{ scope.row.balance || 0 }}</span>
                  <div class="balance-indicator" :class="getBalanceLevel(scope.row.balance)"></div>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="游玩时间" width="120" align="center">
              <template #default="scope">
                <div class="play-time">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatPlayTime(scope.row.play_time || 0) }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="角色" width="100" align="center">
              <template #default="scope">
                <el-tag
                  :type="scope.row.role === 'admin' ? 'danger' : 'primary'"
                  class="role-tag"
                  effect="dark"
                >
                  {{ scope.row.role === 'admin' ? '管理员' : '用户' }}
                </el-tag>
              </template>
            </el-table-column>

            <el-table-column label="状态" width="100" align="center">
              <template #default="scope">
                <div class="status-indicator">
                  <div :class="['status-dot', scope.row.status]"></div>
                  <span :class="['status-text', scope.row.status]">
                    {{ scope.row.status === 'active' ? '正常' : '禁用' }}
                  </span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="注册时间" width="150">
              <template #default="scope">
                <div class="register-time">
                  <el-icon><Calendar /></el-icon>
                  <span>{{ formatDateTime(scope.row.created_at) }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" width="240" fixed="right" align="center">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button
                    type="primary"
                    size="small"
                    @click="editUser(scope.row)"
                    class="action-btn-small"
                  >
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button
                    type="warning"
                    size="small"
                    @click="manageBalance(scope.row)"
                    class="action-btn-small"
                  >
                    <el-icon><Wallet /></el-icon>
                    充值
                  </el-button>
                  <el-button
                    :type="scope.row.status === 'active' ? 'danger' : 'success'"
                    size="small"
                    @click="handleToggleUserStatus(scope.row)"
                    class="action-btn-small"
                  >
                    <el-icon v-if="scope.row.status === 'active'"><Lock /></el-icon>
                    <el-icon v-else><Unlock /></el-icon>
                    {{ scope.row.status === 'active' ? '禁用' : '启用' }}
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <div class="pagination-info">
            <span class="total-info">
              共 {{ pagination.total }} 条记录，第 {{ pagination.page }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
            </span>
          </div>
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            class="modern-pagination"
          />
        </div>
      </div>
    </div>

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="500px"
    >
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="显示名称" prop="real_name">
          <el-input v-model="editForm.real_name" />
        </el-form-item>
        <el-form-item label="游玩时间" prop="play_time">
          <el-input-number 
            v-model="editForm.play_time" 
            :min="0" 
            :step="30"
            controls-position="right"
          />
          <span style="margin-left: 10px; color: #909399;">分钟</span>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="editForm.role" style="width: 100%">
            <el-option label="普通用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="账户状态" prop="status">
          <el-select v-model="editForm.status" style="width: 100%">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser" :loading="saving">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 余额管理对话框 -->
    <el-dialog
      v-model="balanceDialogVisible"
      title="余额管理"
      width="400px"
    >
      <div class="balance-info">
        <p><strong>用户:</strong> {{ selectedUser?.username }}</p>
        <p><strong>当前余额:</strong> ¥{{ selectedUser?.balance || 0 }}</p>
      </div>
      
      <el-form :model="balanceForm" :rules="balanceRules" ref="balanceFormRef" label-width="100px">
        <el-form-item label="操作类型" prop="type">
          <el-radio-group v-model="balanceForm.type">
            <el-radio label="add">充值</el-radio>
            <el-radio label="subtract">扣减</el-radio>
            <el-radio label="set">设置</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number 
            v-model="balanceForm.amount" 
            :min="0" 
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="balanceForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入操作备注"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="balanceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveBalance" :loading="saving">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getUsers, getUserStats, updateUser, updateUserBalance, toggleUserStatus, deleteUser } from '@/api/admin';
import {
  User,
  Download,
  Refresh,
  Search,
  DataAnalysis,
  TrendCharts,
  PieChart,
  Histogram,
  List,
  Clock,
  Calendar,
  Edit,
  Wallet,
  Lock,
  Unlock
} from '@element-plus/icons-vue';

export default {
  name: 'UserManagement',
  components: {
    User,
    Download,
    Refresh,
    Search,
    DataAnalysis,
    TrendCharts,
    PieChart,
    Histogram,
    List,
    Clock,
    Calendar,
    Edit,
    Wallet,
    Lock,
    Unlock
  },
  setup() {
    const loading = ref(false);
    const saving = ref(false);
    const editDialogVisible = ref(false);
    const balanceDialogVisible = ref(false);
    const editFormRef = ref();
    const balanceFormRef = ref();
    const selectedUser = ref(null);
    const showCharts = ref(true); // 控制图表显示

    // 筛选表单
    const filterForm = reactive({
      username: '',
      phone: '',
      role: '',
      status: ''
    });

    // 用户数据
    const users = ref([]);

    // 分页
    const pagination = reactive({
      page: 1,
      pageSize: 10,
      total: 0
    });

    // 编辑表单
    const editForm = reactive({
      id: '',
      username: '',
      email: '',
      phone: '',
      real_name: '',
      play_time: 0,
      role: 'user',
      status: 'active'
    });

    // 余额表单
    const balanceForm = reactive({
      type: 'add',
      amount: 0,
      remark: ''
    });

    // 编辑表单验证规则
    const editRules = {
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      real_name: [
        { required: true, message: '请输入显示名称', trigger: 'blur' }
      ]
    };

    // 余额表单验证规则
    const balanceRules = {
      amount: [
        { required: true, message: '请输入金额', trigger: 'blur' },
        { type: 'number', min: 0, message: '金额不能小于0', trigger: 'blur' }
      ],
      remark: [
        { required: true, message: '请输入操作备注', trigger: 'blur' }
      ]
    };



    // 用户统计数据
    const userStats = ref({
      registrationStats: {},
      totalUsers: 0,
      activeUsers: 0,
      balanceRanges: {}
    });

    // 获取用户统计数据
    const fetchUserStats = async () => {
      try {
        const response = await getUserStats();
        if (response.success) {
          userStats.value = response.data;
        }
      } catch (error) {
        console.error('获取用户统计失败:', error);
      }
    };

    // 用户注册趋势图配置
    const userRegistrationChartOption = computed(() => {
      const registrationData = userStats.value.registrationStats || {};
      console.log('图表数据:', registrationData);

      // 获取所有有数据的月份，并补充最近6个月
      const allMonths = new Set();
      const now = new Date();

      // 添加数据库中存在的月份
      Object.keys(registrationData).forEach(monthKey => {
        allMonths.add(monthKey);
      });

      // 添加最近6个月（确保显示完整）
      for (let i = 5; i >= 0; i--) {
        const date = new Date(now.getFullYear(), now.getMonth() - i, 1);
        const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        allMonths.add(monthKey);
      }

      // 排序并生成图表数据
      const sortedMonths = Array.from(allMonths).sort();
      const months = [];
      const registrations = [];

      sortedMonths.forEach(monthKey => {
        const [year, month] = monthKey.split('-');
        const date = new Date(parseInt(year), parseInt(month) - 1, 1);
        const monthLabel = date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'short' });

        months.push(monthLabel);
        registrations.push(registrationData[monthKey] || 0);
      });

      console.log('图表月份:', months);
      console.log('图表数据:', registrations);

      return {
        title: {
          text: '用户注册趋势',
          left: 'center',
          textStyle: { fontSize: 14 }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}人'
        },
        xAxis: {
          type: 'category',
          data: months
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        series: [{
          data: registrations,
          type: 'line',
          smooth: true,
          itemStyle: { color: '#409eff' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
              ]
            }
          }
        }]
      };
    });

    // 用户角色分布图配置
    const userRoleChartOption = computed(() => {
      const totalUsers = userStats.value.totalUsers || 0;
      const adminCount = 1; // 假设只有一个管理员
      const userCount = totalUsers;

      const roleData = [
        { value: userCount, name: '普通用户' },
        { value: adminCount, name: '管理员' }
      ];

      return {
        title: {
          text: '角色分布',
          left: 'center',
          textStyle: { fontSize: 14 }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        series: [{
          name: '用户角色',
          type: 'pie',
          radius: '60%',
          data: roleData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
    });

    // 用户余额分布图配置
    const userBalanceChartOption = computed(() => {
      const balanceData = userStats.value.balanceRanges || {};

      const balanceRanges = [
        { range: '0-100', count: balanceData['0-100'] || 0, color: '#f56c6c' },
        { range: '101-300', count: balanceData['101-300'] || 0, color: '#e6a23c' },
        { range: '301-500', count: balanceData['301-500'] || 0, color: '#409eff' },
        { range: '500+', count: balanceData['500+'] || 0, color: '#67c23a' }
      ];

      return {
        title: {
          text: '用户余额分布',
          left: 'center',
          textStyle: { fontSize: 14 }
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}: {c}人'
        },
        xAxis: {
          type: 'category',
          data: balanceRanges.map(item => item.range)
        },
        yAxis: {
          type: 'value',
          minInterval: 1
        },
        series: [{
          data: balanceRanges.map((item, index) => ({
            value: item.count,
            itemStyle: { color: item.color }
          })),
          type: 'bar',
          barWidth: '60%'
        }]
      };
    });

    // 格式化日期时间
    const formatDateTime = (dateStr) => {
      if (!dateStr) return '未知';
      return new Date(dateStr).toLocaleString('zh-CN');
    };

    // 格式化游玩时间
    const formatPlayTime = (minutes) => {
      if (minutes < 60) {
        return `${minutes}分钟`;
      }
      const hours = Math.floor(minutes / 60);
      const remainingMinutes = minutes % 60;
      return `${hours}小时${remainingMinutes}分钟`;
    };

    // 获取余额等级
    const getBalanceLevel = (balance) => {
      if (balance >= 1000) return 'high';
      if (balance >= 500) return 'medium';
      if (balance >= 100) return 'low';
      return 'empty';
    };

    // 刷新数据
    const refreshData = async () => {
      await Promise.all([
        fetchUsers(),
        fetchUserStats()
      ]);
      ElMessage.success('数据刷新成功');
    };

    // 获取用户列表
    const fetchUsers = async () => {
      loading.value = true;
      try {
        const params = {
          page: pagination.page,
          pageSize: pagination.pageSize,
          role: filterForm.role,
          status: filterForm.status,
          search: filterForm.username || filterForm.phone
        };

        console.log('请求用户列表参数:', params);
        const response = await getUsers(params);
        console.log('用户列表响应:', response);

        if (response.success) {
          users.value = response.data.items || response.data.users || [];
          pagination.total = response.data.total || 0;
          pagination.page = response.data.page || 1;
          pagination.pageSize = response.data.pageSize || 10;
        }
      } catch (error) {
        console.error('获取用户列表失败:', error);
        ElMessage.error('获取用户列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 搜索用户
    const searchUsers = () => {
      pagination.page = 1; // 重置到第一页
      fetchUsers(); // 重新获取数据
    };

    // 重置筛选条件
    const resetFilter = () => {
      filterForm.username = '';
      filterForm.phone = '';
      filterForm.role = '';
      filterForm.status = '';
      pagination.page = 1;
      fetchUsers(); // 重新获取数据
    };

    // 编辑用户
    const editUser = (user) => {
      selectedUser.value = user;
      Object.assign(editForm, {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        real_name: user.real_name,
        play_time: user.play_time || 0,
        role: user.role,
        status: user.status
      });
      editDialogVisible.value = true;
    };

    // 保存用户信息
    const saveUser = async () => {
      try {
        await editFormRef.value.validate();
        saving.value = true;

        // 调用后端API更新用户信息
        const response = await updateUser(editForm.id, {
          username: editForm.username,
          email: editForm.email,
          real_name: editForm.real_name,
          role: editForm.role,
          status: editForm.status
        });

        if (response.success) {
          ElMessage.success('用户信息更新成功');
          editDialogVisible.value = false;
          // 重新获取用户列表
          await fetchUsers();
        } else {
          ElMessage.error(response.message || '更新失败');
        }
      } catch (error) {
        console.error('保存失败:', error);
        ElMessage.error('保存失败，请稍后重试');
      } finally {
        saving.value = false;
      }
    };

    // 管理余额
    const manageBalance = (user) => {
      selectedUser.value = user;
      balanceForm.type = 'add';
      balanceForm.amount = 0;
      balanceForm.remark = '';
      balanceDialogVisible.value = true;
    };

    // 保存余额操作
    const saveBalance = async () => {
      try {
        await balanceFormRef.value.validate();
        saving.value = true;

        // 调用后端API更新用户余额
        const response = await updateUserBalance(selectedUser.value.id, {
          amount: balanceForm.amount,
          operation: balanceForm.type,
          remark: balanceForm.remark
        });

        if (response.success) {
          ElMessage.success('余额操作成功');
          balanceDialogVisible.value = false;
          // 重新获取用户列表
          await fetchUsers();
        } else {
          ElMessage.error(response.message || '余额操作失败');
        }
      } catch (error) {
        console.error('余额操作失败:', error);
        ElMessage.error('余额操作失败，请稍后重试');
      } finally {
        saving.value = false;
      }
    };

    // 切换用户状态
    const handleToggleUserStatus = async (user) => {
      const action = user.status === 'active' ? '禁用' : '启用';
      const newStatus = user.status === 'active' ? 'inactive' : 'active';

      try {
        await ElMessageBox.confirm(
          `确认${action}用户 ${user.username}？`,
          `${action}用户`,
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );

        // 调用后端API切换用户状态
        const response = await toggleUserStatus(user.id, newStatus);

        if (response.success) {
          ElMessage.success(`用户${action}成功`);
          // 重新获取用户列表
          await fetchUsers();
        } else {
          ElMessage.error(response.message || `用户${action}失败`);
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('切换用户状态失败:', error);
          ElMessage.error('操作失败，请稍后重试');
        }
      }
    };

    // 图表切换处理
    const handleChartsToggle = (value) => {
      if (value) {
        // 显示图表时刷新数据
        fetchUserStats();
      }
    };

    // 刷新图表数据
    const refreshCharts = async () => {
      await fetchUserStats();
      ElMessage.success('图表数据已刷新');
    };

    // 导出用户数据
    const exportUsers = async () => {
      try {
        // 获取当前筛选条件下的所有用户数据
        const params = {
          page: 1,
          pageSize: 1000, // 获取大量数据用于导出
          role: filterForm.role,
          status: filterForm.status,
          search: filterForm.username || filterForm.phone
        };

        const response = await getUsers(params);
        if (response.success) {
          const users = response.data.items || response.data.users;

          // 准备导出数据
          const exportData = users.map(user => ({
            '用户ID': user.id,
            '用户名': user.username,
            '真实姓名': user.real_name || '',
            '手机号': user.phone,
            '邮箱': user.email,
            '角色': user.role === 'admin' ? '管理员' : '普通用户',
            '状态': user.status === 'active' ? '正常' : '禁用',
            '余额': user.balance || 0,
            '游玩时间(分钟)': user.play_time || 0,
            '注册时间': formatDateTime(user.created_at),
            '更新时间': formatDateTime(user.updated_at)
          }));

          // 转换为CSV格式
          const csvContent = convertToCSV(exportData);

          // 下载文件
          downloadCSV(csvContent, `用户数据_${new Date().toLocaleDateString()}.csv`);

          ElMessage.success(`成功导出 ${users.length} 条用户数据`);
        }
      } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出数据失败');
      }
    };

    // 转换为CSV格式
    const convertToCSV = (data) => {
      if (!data.length) return '';

      const headers = Object.keys(data[0]);
      const csvRows = [];

      // 添加表头
      csvRows.push(headers.join(','));

      // 添加数据行
      data.forEach(row => {
        const values = headers.map(header => {
          const value = row[header];
          // 处理包含逗号的值
          return typeof value === 'string' && value.includes(',')
            ? `"${value}"`
            : value;
        });
        csvRows.push(values.join(','));
      });

      return csvRows.join('\n');
    };

    // 下载CSV文件
    const downloadCSV = (csvContent, filename) => {
      const blob = new Blob(['\uFEFF' + csvContent], {
        type: 'text/csv;charset=utf-8;'
      });
      const link = document.createElement('a');

      if (link.download !== undefined) {
        const url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.page = 1;
      fetchUsers(); // 重新获取数据
    };

    const handleCurrentChange = (page) => {
      pagination.page = page;
      fetchUsers(); // 重新获取数据
    };

    onMounted(() => {
      fetchUsers();
      fetchUserStats(); // 初始化时获取统计数据
    });

    return {
      loading,
      saving,
      editDialogVisible,
      balanceDialogVisible,
      editFormRef,
      balanceFormRef,
      selectedUser,
      showCharts,
      filterForm,
      users,
      pagination,
      editForm,
      balanceForm,
      editRules,
      balanceRules,
      userStats,
      userRegistrationChartOption,
      userRoleChartOption,
      userBalanceChartOption,
      formatDateTime,
      formatPlayTime,
      getBalanceLevel,
      refreshData,
      fetchUsers,
      fetchUserStats,
      searchUsers,
      resetFilter,
      editUser,
      saveUser,
      manageBalance,
      saveBalance,
      handleToggleUserStatus,
      handleChartsToggle,
      refreshCharts,
      exportUsers,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.user-management-container {
  padding: 24px;
  background: #f8fafc;
  min-height: calc(100vh - 60px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 32px;
  border-radius: 20px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
  color: white;
  position: relative;
  overflow: hidden;
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  transform: translate(50%, -50%);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 20px;
  z-index: 1;
}

.header-icon {
  width: 64px;
  height: 64px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  backdrop-filter: blur(10px);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 16px;
  z-index: 1;
}

.action-btn {
  border: none !important;
  border-radius: 12px !important;
  padding: 12px 24px !important;
  font-weight: 600 !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px);
}

.action-btn.primary {
  background: rgba(255, 255, 255, 0.2) !important;
  color: white !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
}

.action-btn.primary:hover {
  background: rgba(255, 255, 255, 0.3) !important;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(255, 255, 255, 0.3);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1) !important;
  color: white !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2) !important;
  transform: translateY(-2px);
}

.header-decoration {
  position: absolute;
  top: 50%;
  right: 80px;
  transform: translateY(-50%);
  z-index: 1;
}

.decoration-circle {
  width: 150px;
  height: 150px;
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  position: relative;
}

.decoration-dots {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.decoration-dots .dot {
  width: 6px;
  height: 6px;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 50%;
  animation: float 3s ease-in-out infinite;
}

.decoration-dots .dot:nth-child(2) {
  animation-delay: 0.5s;
}

.decoration-dots .dot:nth-child(3) {
  animation-delay: 1s;
}

@keyframes float {
  0%, 100% { transform: translateY(0); opacity: 0.4; }
  50% { transform: translateY(-8px); opacity: 1; }
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 32px;
}

.filter-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.filter-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.filter-title .el-icon {
  color: #667eea;
}

.reset-btn {
  color: #64748b !important;
  font-size: 14px !important;
}

.reset-btn:hover {
  color: #667eea !important;
}

.filter-content {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  gap: 24px;
  align-items: end;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 4px;
}

.filter-input,
.filter-select {
  width: 100%;
}

.search-group {
  position: relative;
}

.search-actions {
  display: flex;
  gap: 12px;
}

.search-btn {
  width: 100%;
  border-radius: 12px !important;
  font-weight: 600 !important;
}

/* 切换区域 */
.toggle-section {
  margin-bottom: 32px;
}

.toggle-card {
  background: white;
  border-radius: 16px;
  padding: 20px 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #e2e8f0;
}

.toggle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.toggle-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.toggle-title .el-icon {
  color: #667eea;
}

.toggle-controls {
  display: flex;
  align-items: center;
  gap: 16px;
}

.chart-switch {
  --el-switch-on-color: #667eea;
}

.refresh-charts-btn {
  border-radius: 8px !important;
  font-weight: 500 !important;
}

/* 图表区域 */
.charts-section {
  margin-bottom: 32px;
  transition: all 0.3s ease;
}

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 24px;
}

.chart-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f1f5f9;
}

.chart-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  font-weight: 600;
  color: #1e293b;
}

.chart-title .el-icon {
  color: #667eea;
  font-size: 20px;
}

.chart-tag {
  border-radius: 8px !important;
  font-weight: 500 !important;
}

.chart-container {
  height: 280px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 表格区域 */
.table-section {
  margin-bottom: 32px;
}

.table-card {
  background: white;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid #e2e8f0;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
}

.table-title .el-icon {
  color: #667eea;
}

.user-count {
  font-size: 14px;
  color: #64748b;
  font-weight: 500;
  margin-left: 8px;
}

.table-actions .el-button-group .el-button {
  border-radius: 8px !important;
  font-weight: 500 !important;
}

.table-container {
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.modern-table {
  border-radius: 12px;
}

.modern-table .el-table__row {
  transition: all 0.3s ease;
}

.modern-table .el-table__row:hover {
  background: #f8fafc !important;
}

/* 用户信息样式 */
.user-id {
  font-weight: 600;
  color: #667eea;
  background: #f0f4ff;
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username {
  font-weight: 600;
  color: #1e293b;
  font-size: 14px;
}

.real-name {
  font-size: 12px;
  color: #64748b;
}

.phone-number,
.email-text {
  font-size: 14px;
  color: #374151;
}

/* 余额样式 */
.balance-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.balance-amount {
  font-weight: 700;
  font-size: 16px;
  color: #059669;
}

.balance-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.balance-indicator.high {
  background: #10b981;
  box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
}

.balance-indicator.medium {
  background: #f59e0b;
  box-shadow: 0 0 0 2px rgba(245, 158, 11, 0.2);
}

.balance-indicator.low {
  background: #ef4444;
  box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.2);
}

.balance-indicator.empty {
  background: #9ca3af;
  box-shadow: 0 0 0 2px rgba(156, 163, 175, 0.2);
}

/* 游玩时间样式 */
.play-time {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #374151;
}

.play-time .el-icon {
  color: #667eea;
}

/* 角色标签样式 */
.role-tag {
  border-radius: 8px !important;
  font-weight: 600 !important;
  padding: 4px 8px !important;
}

/* 状态指示器 */
.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  position: relative;
}

.status-dot.active {
  background: #10b981;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);
}

.status-dot.inactive {
  background: #ef4444;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.2);
}

.status-text {
  font-size: 12px;
  font-weight: 600;
}

.status-text.active {
  color: #059669;
}

.status-text.inactive {
  color: #dc2626;
}

/* 注册时间样式 */
.register-time {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #64748b;
}

.register-time .el-icon {
  color: #667eea;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 2px;
  flex-wrap: wrap;
  justify-content: center;
}

.action-btn-small {
  border-radius: 8px !important;
  font-weight: 500 !important;
  font-size: 12px !important;
  padding: 6px 12px !important;
  transition: all 0.3s ease !important;
}

.action-btn-small:hover {
  transform: translateY(-1px) !important;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e2e8f0;
}

.pagination-info {
  font-size: 14px;
  color: #64748b;
}

.total-info {
  font-weight: 500;
}

.modern-pagination {
  --el-pagination-button-color: #374151;
  --el-pagination-hover-color: #667eea;
  --el-pagination-bg-color: white;
  --el-pagination-current-bg-color: #667eea;
}



.balance-info p {
  margin: 8px 0;
  color: #374151;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-content {
    grid-template-columns: 1fr 1fr 1fr;
  }

  .charts-grid {
    grid-template-columns: 1fr;
  }

  .header-decoration {
    display: none;
  }
}

@media (max-width: 768px) {
  .user-management-container {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
    padding: 24px;
  }

  .header-left {
    flex-direction: column;
    gap: 16px;
  }

  .header-actions {
    width: 100%;
    justify-content: center;
  }

  .filter-content {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .table-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-btn-small {
    width: 100%;
    justify-content: center;
  }

  .pagination-container {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .user-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .page-header {
    padding: 20px;
  }

  .header-content h1 {
    font-size: 24px;
  }

  .filter-card,
  .toggle-card,
  .chart-card,
  .table-card {
    padding: 16px;
  }

  .modern-table {
    font-size: 12px;
  }

  .action-btn-small {
    font-size: 11px !important;
    padding: 4px 8px !important;
  }
}
</style>
